<?php

namespace home\controller;
//引入公共控制器
use \core\Controller;
class UserController extends Controller{
    //登录
    public function check(){
        //接收数据
        $u_username = trim($_POST['u_username']);
        $u_password = trim($_POST['u_password']);
        //验证密码的合法性
        if (empty($u_username) || empty($u_password)){
            $this->error('<script>alert("用户名和密码不能为空")</script>','index','index');
        }
        //有效性验证
        $u = new \home\model\UserModel();
        if (!$user = $u->checkUsername($u_username)){
            $this->error('当前用户'.$u_username.'不存在','index','index');
        }
        //密码处理
        if (md5($u_password) !== $user['u_password']){
            $this->error('<script>alert("密码错误")</script>','index','index');
        }
        //存放到session
        //存放到session
        @session_start();
        $_SESSION['user'] = $user;
        //继续回到首页
        $this->success('<script>alert("登录成功")</script>','index','index');
    }
    public function logout(){
        //启动session
        @session_start();
        session_destroy();
        $this->success('<script>alert("退出成功")</script>','index','index');

    }
    //生产验证码图片
    public function captcha(){
        //增加验证码的图片
        \vendor\Captcha::getCaptcha();
    }
    //注册功能
    public function register(){
        //接收数据
        $data['u_username']=trim($_POST['u_username']);
        $data['u_password'] = trim($_POST['u_password']);
        $captcha=trim($_POST['captcha']);
        //验证验证吗的合法性
        if (empty($captcha)){
            $this->error('<script>alert("验证码不得为空")</script>','index','index');
        }
        if (empty($data['u_username']) || empty($data['u_password'])){
            $this->back('<script>alert("用户名和密码不得为空")</script>');
        }
        //验证验证码的有效
        if (!\vendor\Captcha::checkCaptcha($captcha)){
            $this->back('<script>alert("验证码错误")</script>');
        }
        //用户名验证
        $u=new \home\model\UserModel();
        if ($u->checkUsername($data['u_username'])){
            $this->back('用户名'.$data['u_username'].'已经存在');
        }
        //注册补充数据
        $data['u_res_time']=time();
        if ($u->autoInsert($data)){
            $this->success('<script>alert("用户注册成功")</script>','index','index');
        }else{
            $this->error('<script>alert("用户注册失败")</script>','index','index');
        }
    }
}
